﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace JsonTest
{
    public static class JsonDictConverter
    {
        public static JsonDictConverter<TKey, TValue> Gen<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            return new JsonDictConverter<TKey, TValue>();
        }

        public static KeyValuePairShell<TKey, TValue> GenKeyValuePairShell<TKey, TValue>(KeyValuePair<TKey, TValue> item)
        {
            return new KeyValuePairShell<TKey, TValue>(item.Key, item.Value);
        }
    }

    public class JsonDictConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
    {
        public override Dictionary<TKey, TValue>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var c = JsonSerializer.Deserialize(ref reader, typeof(List<KeyValuePairShell<TKey, TValue>>), options) as List<KeyValuePairShell<TKey, TValue>>;

            var dictionary = new Dictionary<TKey, TValue>();
            foreach (var kv in c)
            {
                dictionary.Add(kv.Key, kv.Value);
            }
            return dictionary;
        }

        public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializerOptions options)
        {
            var c = value.Select(kvp => new KeyValuePairShell<TKey, TValue>(kvp.Key, kvp.Value)).ToList();
            var str = JsonSerializer.Serialize(c, options);
            writer.WriteRawValue(str);
        }
    }

    public class KeyValuePairShell<TKey, TValue>
    {
        public KeyValuePairShell(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public TKey Key { get; set; }
        public TValue Value { get; set; }
    }
}
